using UnityEngine;

public class ShadyBattleState : EnemyState
{
    private new Shady Enemy => (Shady)base.Enemy;

    private int moveDirection;
    private float defaultSpeed;

    public ShadyBattleState(Enemy enemy, string animName) : base(enemy, animName) { }

    public override void Enter()
    {
        base.Enter();
        defaultSpeed = Enemy.moveSpeed;
        Enemy.moveSpeed = Enemy.battleMoveSpeed;
        if (PlayerManager.Instance.Player.Stats.IsDead)
            StateMachine.ChangeTo(Enemy.IdleState);
    }

    public override void Update()
    {
        base.Update();
        if (Enemy.Player)
        {
            stateTimer = Enemy.battleTime;
            if (Vector3.Distance(Enemy.transform.position, Enemy.Player.transform.position) <= 2)
            {
                Enemy.Stats.KillEntity(); // this enteres dead state which triggers explosion + drop items and souls
            }
        }
        else
        {
            if (stateTimer <= 0) //  || Vector2.Distance(Enemy.Player.transform.position, Enemy.transform.position) > 2
            {
                StateMachine.ChangeTo(Enemy.IdleState);
            }
        }
        if (Enemy.Player.transform.position.x > Enemy.transform.position.x)
        {
            moveDirection = 1;
        }
        else if (Enemy.Player.transform.position.x < Enemy.transform.position.x)
        {
            moveDirection = -1;
        }
        Enemy.SetVelocity(moveDirection * Enemy.moveSpeed, Rb.velocity.y);
    }

    public override void Exit()
    {
        base.Exit();
        Enemy.moveSpeed = defaultSpeed;
    }

    private bool CanAttack()
    {
        if (Time.time >= Enemy.lastTimeAttacked + Enemy.attackCooldown)
        {
            Enemy.attackCooldown = Random.Range(Enemy.minAttackCooldown, Enemy.maxAttackCooldown);
            Enemy.lastTimeAttacked = Time.time;
            return true;
        }
        return false;
    }
}
